package com.zhaodm.practise.client;

import java.util.List;

import com.zhaodm.practise.service.IPet;
import com.zhaodm.practise.service.Person;
import com.zhaodm.practise.service.Pet;

import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class ComplexClient extends Activity {
	
	private IPet petService;
	private Button get;
	private EditText personView;
	private ListView showView;
	private final static String TAG = "Complex Client";
	
	private ServiceConnection conn = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			petService = IPet.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			petService = null;
		}
		
	};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        personView = (EditText)findViewById(R.id.person);
        showView = (ListView)findViewById(R.id.show);
        get = (Button)findViewById(R.id.getServiceStatus);
        
        Intent intent = new Intent();
        intent.setAction("com.zhaodm.practise.service.COMPLEX_SERVICE");
        
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
        get.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					String personName = personView.getText().toString();
					Log.i(TAG, "input person name ======= "+personName);
					List<Pet> pets = petService.getPets(new Person(1, personName, personName+"_pass"));
					ArrayAdapter<Pet> adapter = new ArrayAdapter<Pet>(ComplexClient.this, android.R.layout.simple_list_item_1, pets);
					showView.setAdapter(adapter);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
        	
        });
    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onDestroy()
     */
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	this.unbindService(conn);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
